package com.lishe.lishe.lishe.module.mall.fragment;

import android.app.Activity;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.R;
import com.lishe.lishe.lishe.base.BaseFragment;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.mall.activity.MallGoodsActivity;
import com.lishe.lishe.lishe.adapter.ImageViewPagerAdapter;
import com.lishe.lishe.lishe.module.mall.bean.MallGoods;
import com.lishe.lishe.lishe.module.mall.bean.SkuObject;
import com.lishe.lishe.lishe.module.mall.http.HttpMall;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.LinkedList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

/**
 * Created by shino on 2017/9/19.
 * 商品详情页
 */

public class GoodsDetailFragent extends BaseFragment implements View.OnClickListener {

    private ViewPager viewPager;
    private LinearLayout pointLayout;
    private LinearLayout goodsListLayout;
    private TextView name;
    private TextView discount;
    private TextView discountIntegral;
    private TextView integral;
    private TextView goodsNo;
    private TextView goodsWeight;
    private TextView goodsBrand;
    private String itemId;
    private ImageLoaderUtils imageLoaderUtils;
    private ImageViewPagerAdapter viewPagerAdapter;
    private int pageIndex = 0;
    private int oldIndex = 0;
    private int status = 1;


    private LinkedList<MallGoods> mallGoodsItems = new LinkedList<>();//滚动栏的商品
    private LinkedList<String> images = new LinkedList<>();//轮播的图片地址
    private LinkedList<SkuObject> skus = new LinkedList<>();//skus
    private LinkedList<ImageView> imageViews = new LinkedList<>();//轮播的图片
    private LinkedList<View> points = new LinkedList<>();//轮播的图片的小圆点
    private MallGoods mallGoods = new MallGoods();//
    private LinkedList<String> lisAddress = new LinkedList<>();

    public static GoodsDetailFragent newInstance(String itemId) {
        GoodsDetailFragent fragment = new GoodsDetailFragent();
        Bundle bundle = new Bundle();
        bundle.putString("itemId", itemId);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        itemId = getArguments().getString("itemId");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_goods_detail, null);
        imageLoaderUtils = new ImageLoaderUtils();
        viewPagerAdapter = new ImageViewPagerAdapter(imageViews);
        initView(view);
        view.setOnTouchListener(this);
        return view;
    }

    private void initView(View v) {
        viewPager = v.findViewById(R.id.view_pager);
        viewPager.setAdapter(viewPagerAdapter);
        pointLayout = v.findViewById(R.id.point_layout);
        goodsListLayout = v.findViewById(R.id.goods_list_layout);
        name = v.findViewById(R.id.name);
        discount = v.findViewById(R.id.discount);
        discountIntegral = v.findViewById(R.id.discount_integral);
        integral = v.findViewById(R.id.integral);
        goodsNo = v.findViewById(R.id.goods_no);
        goodsWeight = v.findViewById(R.id.goods_weight);
        goodsBrand = v.findViewById(R.id.goods_brand);
        setOnlistener();
        getData();
    }

    private void setOnlistener() {
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                points.get(oldIndex).setBackgroundResource(R.drawable.shape_coner50px);
                points.get(position).setBackgroundResource(R.drawable.shape_red50px);
                pageIndex = position;
                oldIndex = position;
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View view) {

    }

    //-------------------------轮播图小圆点变化控制--------------
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (pageIndex < images.size() - 1) {
                pageIndex += 1;
            } else {
                pageIndex = 0;
            }
            handler.postDelayed(this, 3000);
            viewPager.setCurrentItem(pageIndex, false);
        }
    };

    private void getData() {
        if (itemId != null) {
            LoadingUtils.createLoadingDialog(getActivity(), "请稍后...", true);
            HttpMall.getGoodsDetailInfo(Globals.getToken(), itemId, getGoodsDetailRespose);
        }
    }


    /**
     * 数据初始化
     */
    private void initdata() {
        imageViews.clear();
        points.clear();
        pointLayout.removeAllViews();
        ViewGroup.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        RelativeLayout.LayoutParams rparams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        viewPager.setLayoutParams(rparams);
        for (String url : images) {
            //图片
//          ImageView imageView = new ImageView(getActivity());
            ImageView imageView = (ImageView) getActivity().getLayoutInflater().inflate(R.layout.item_imageview, null);
            imageView.setLayoutParams(params);
            imageView.setAdjustViewBounds(true);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageLoaderUtils.displayImage(url, imageView);
            imageViews.add(imageView);
            //小圆点
            View pointView = getActivity().getLayoutInflater().inflate(R.layout.item_carousel_point, null);
            View point = pointView.findViewById(R.id.point);
            pointLayout.addView(pointView);
            points.add(point);
        }
        goodsListLayout.removeAllViews();
        for (final MallGoods mall : mallGoodsItems) {//滚动栏内容
            View goodsLayout = getActivity().getLayoutInflater().inflate(R.layout.item_mall_scroll, null);
            ImageView goods_img = goodsLayout.findViewById(R.id.goods_img);
            TextView goods_name = goodsLayout.findViewById(R.id.goods_name);
            TextView integral = goodsLayout.findViewById(R.id.integral);
            Log.e("url", mall.getImage_default_id());
            imageLoaderUtils.displayImage(mall.getImage_default_id(), goods_img);
            goods_name.setText(mall.getTitle());
            goodsLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    MallGoodsActivity.jump(getActivity(), mall.getItem_id());
                }
            });
            integral.setText((int) ((float) mall.getPrice() * 100) + "");
            goodsListLayout.addView(goodsLayout);
        }
        viewPagerAdapter.notifyDataSetChanged();
        name.setText(mallGoods.getTitle());
        discountIntegral.setText((int) ((float) mallGoods.getPrice() * 100) + "");
        if (mallGoods.getDiscount() == 0) {
            discount.setVisibility(View.GONE);
        } else {
            discount.setVisibility(View.VISIBLE);
            discount.setText(String.format("%.1f", mallGoods.getDiscount() * 10) + "折");
        }
        if (mallGoods.getMkt_price() > 0) {
            integral.setVisibility(View.VISIBLE);
            integral.setText((int) ((float) mallGoods.getMkt_price() * 100) + "积分");
        } else {
            integral.setVisibility(View.GONE);
        }
        integral.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        goodsBrand.setText(mallGoods.getBrand());
        goodsWeight.setText(String.format("%.2f", Float.parseFloat(mallGoods.getWeight())) + "kg");
        goodsNo.setText(mallGoods.getItem_id());
        viewPager.setCurrentItem(0);
        points.get(0).setBackgroundResource(R.drawable.shape_red50px);
        handler.removeCallbacks(runnable);
        handler.postDelayed(runnable, 3000);
    }

    public MallGoods getMallObject() {
        return mallGoods;
    }

    /**
     * 商品详情
     */
    AsyncHttpResponseHandler getGoodsDetailRespose = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            String result = new String(responseBody);
            LoadingUtils.closeDialog();
            Log.e("商品详情", result);
            try {
                JSONObject json = new JSONObject(result);
                if (0 == json.optInt("errcode") && 100 == json.optInt("result")) {
                    JSONObject dataObject = json.optJSONObject("data");
                    JSONObject itemInfo = dataObject.optJSONObject("itemInfo");
                    JSONObject itemStatus = dataObject.optJSONObject("itemStatus");
                    mallGoods.setApprove_status(itemStatus.optString("approve_status"));
                    mallGoods.setShop_id(itemStatus.optString("shop_id"));
                    JSONObject brand_id = itemInfo.optJSONObject("brand_id");
                    mallGoods.setBrand(brand_id.optString("brand_name"));
                    mallGoods.setMkt_price(itemInfo.optDouble("mkt_price"));
                    mallGoods.setPrice(itemInfo.optDouble("price"));
                    mallGoods.setTitle(itemInfo.optString("title"));
                    mallGoods.setWeight(itemInfo.optString("weight"));
                    mallGoods.setItem_id(itemInfo.optString("item_id"));
                    mallGoods.setImage_default_id(itemInfo.optString("image_default_id"));
                    mallGoods.setJd_ids(itemInfo.optString("jd_sku"));
                    JSONArray itemList = dataObject.optJSONArray("itemList");
                    JSONArray skuList = dataObject.optJSONArray("skuList");
                    skus.clear();
                    for (int i = 0; i < skuList.length(); i++) {
                        JSONObject skuListObject = skuList.optJSONObject(i);
                        SkuObject skuObject = new SkuObject();
                        if (i == 0) {
                            mallGoods.setKucun(skuListObject.optString("store"));
                            mallGoods.setSku_id(skuListObject.optString("sku_id"));
                            //规格spec_info，空时显示默认
//                            if (!skuListObject.optString("spec_info").equals("") && !skuListObject.optString("spec_info").equals("null")) {
                                skuObject = JSON.parseObject(skuListObject.toString(), SkuObject.class);
                                skus.add(skuObject);
//                            }
                        } else {
                            skuObject = JSON.parseObject(skuListObject.toString(), SkuObject.class);
                            skus.add(skuObject);
                        }
                    }

                    JSONArray new_list_images = itemInfo.optJSONArray("new_list_images");
                    images.clear();
                    for (int i = 0; i < new_list_images.length(); i++) {
                        images.add(new_list_images.optString(i));
                    }
                    mallGoodsItems.clear();
                    for (int i = 0; i < itemList.length(); i++) {
                        JSONObject itemListObject = itemList.optJSONObject(i);
                        MallGoods mall = new MallGoods();
                        mall = JSON.parseObject(itemListObject.toString(), MallGoods.class);
                        mallGoodsItems.add(mall);
                    }
                    //更新UI数据
                    initdata();
                    //改变MallGoodsAcivity的底部按钮
                    Activity activity = getActivity();
                    Log.e("sku",skus.size()+"");
                    initStatus(mallGoods.getApprove_status());
                    if (activity != null && activity instanceof MallGoodsActivity) {
                        ((MallGoodsActivity) getActivity()).chageTate(status);
                    }
                } else {
                    LoadingUtils.closeDialog();
                    String msg = json.optString("msg");
                    toast(msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            LoadingUtils.closeDialog();
            if (isAdded()) {
                toast(getString(R.string.network_or_server_exception));
            }
        }
    };

    public List<SkuObject> getSkus() {
        return skus;
    }
    private void initStatus(String str) {
        status = MallGoodsActivity.ONSALE;
        if (getSkus()!=null&&"0".equals(getSkus().get(0).getStore())) {
            status = MallGoodsActivity.NOGOODS;
        }else{
            if ("onsale".equals(str)) {
                status = MallGoodsActivity.ONSALE;
            } else if ("instock".equals(str)) {
                status = MallGoodsActivity.INSTOCK;
            }
        }

    }
}
